package thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 基于ThreadPoolExecutor类型直接创建线程池
 */
public class ThreadPoolDemo02 {
    private static int corePoolSize = 2;
    private static int maximumPoolSize = 3;
    private static long keepAliveTime = 1;
    private static TimeUnit unit = TimeUnit.SECONDS;
    /**工作队列*/
    private static LinkedBlockingQueue<Runnable> workQueue =
            new LinkedBlockingQueue<>(1);
    /**线程工厂*/
    private static ThreadFactory threadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r);
        }
    };
    /**线程池拒绝策略*/
    private static ThreadPoolExecutor.AbortPolicy handler =
            new ThreadPoolExecutor.AbortPolicy();//默认直接抛异常
    public static void main(String[] args) {
        //1.创建线程池
        ThreadPoolExecutor executor =
                new ThreadPoolExecutor(
                        corePoolSize,
                        maximumPoolSize,
                        keepAliveTime,
                        unit,
                        workQueue,
                        threadFactory,
                        handler);
        //2.执行任务
         executor.execute(()-> {
                    System.out.println(Thread.currentThread().getName()+":task1");
                    try{Thread.sleep(1000);}catch (InterruptedException e){}
         });
          executor.execute(()-> {
            System.out.println(Thread.currentThread().getName()+":task2");
            try{Thread.sleep(1000);}catch (InterruptedException e){}
         });
         executor.execute(()-> {//放队列
            System.out.println(Thread.currentThread().getName()+":task3");
            try{Thread.sleep(1000);}catch (InterruptedException e){}
         });
        executor.execute(()-> {//启动新线程
            System.out.println(Thread.currentThread().getName()+":task4");
            try{Thread.sleep(1000);}catch (InterruptedException e){}
        });
        executor.execute(()-> {//启动新线程
            System.out.println(Thread.currentThread().getName()+":task5");
            try{Thread.sleep(1000);}catch (InterruptedException e){}
        });
        executor.shutdown();
    }
}
